package com.utils;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Vector;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class FileUtil {
	
	public static boolean exists(String filename) {
		try {
			File f = new File(filename);
			return f.exists();
		} catch (Exception e) {
		}
		return false;
	}
	
	/**
	 * Save the file on the hard disk. Returns falure; unsuccessful.
	 * @param filename
	 * @param buffer
	 * @return
	 */
	public static boolean saveFile(String filename, String buffer) {
		try {
			File f = new File(filename);
			if (!f.exists()) {
				f.createNewFile();
			}
			FileOutputStream out = new FileOutputStream(f);
			byte[] data = new byte[buffer.length() + 1];
			buffer.getBytes(0, buffer.length(), data, 0);
			out.write(data, 0, buffer.length());
			out.close();
		} catch (IOException e) {
			System.out.println("FileUtil Error save file: " + filename + ": " + e.toString());
			e.printStackTrace();
			return false;
		}
		return true;
	}

	/**
	 * @param req
	 * @param resp
	 * @param content
	 * @param original_filename
	 * @throws IOException
	 */
	public static void doDownload(HttpServletRequest req,
			HttpServletResponse resp, byte[] content, String original_filename)
			throws IOException {
		int length = content.length;
		ServletOutputStream op = resp.getOutputStream();
		//
		// Set the response and go!
		//
		//
		resp.setContentType("application/octet-stream");
		resp.setContentLength(length);
		resp.setHeader("Content-Disposition", "attachment; filename=\""
				+ original_filename + "\"");

		//
		// Stream to the requester.
		//
		op.write(content, 0, length);
		op.flush();
		op.close();
	}

	/**
	 * @param location
	 * @param fileExt
	 * @return a vector of <code>File</code> objects
	 */
	public static Vector getAllFiles(java.io.File location, String fileExt) {
		Vector v = new Vector();
		java.io.File[] list = location.listFiles();
		for (int i = 0; i < list.length; i++) {
			if (list[i].toString().endsWith(fileExt)) {
				v.addElement(list[i]);
			}
			/* also list file in subfolders */
			// if ((list[i]).isDirectory()) {
			// getAllFiles(list[i]);
			// }
		}
		return v;
	}

	/**
	 * @param source_name
	 * @param dest_name
	 * @throws IOException
	 */
	public static void copy(String source_name, String dest_name)
			throws IOException {
		File source_file = new File(source_name);
		File dest_file = new File(dest_name);
		copy(source_file, dest_file);
	}

	/**
	 * @param source_file
	 * @param dest_file
	 * @throws IOException
	 */
	public static void copy(File source_file, File dest_file)
			throws IOException {
		FileInputStream source = null;
		FileOutputStream destination = null;

		byte[] buffer;
		int bytes_read;

		// First make sure the specified source file
		// exists, is a file, and is readable.
		if (!source_file.exists() || !source_file.isFile())
			throw new FileCopyException("FileCopy: no such source file: "
					+ source_file.getPath());
		if (!source_file.canRead())
			throw new FileCopyException("FileCopy: source file is unreadable: "
					+ source_file.getPath());
		// If we've gotten this far, then everything is okay;
		// we can copy the file.
		source = new FileInputStream(source_file);
		destination = new FileOutputStream(dest_file);
		buffer = new byte[1024];
		while ((bytes_read = source.read(buffer)) != -1) {
			destination.write(buffer, 0, bytes_read);
		}
		// No matter what happens, always close any streams we've opened.
		try {
			if (source != null)
				source.close();
			if (destination != null)
				destination.close();
		} catch (IOException e) {
		}
	}

	/**
	 * @param source_name
	 * @param dest_name
	 * @throws IOException
	 */
	public static void move(String source_name, String dest_name)
			throws IOException {
		File source_file = new File(source_name);
		File dest_file = new File(dest_name);

		copy(source_file, dest_file);
		source_file.delete();
	}

	/**
	 * @param source_file
	 * @param dest_file
	 * @throws IOException
	 */
	public static void move(File source_file, File dest_file)
			throws IOException {
		copy(source_file, dest_file);
		source_file.delete();
	}

	/**
	 * @param filename
	 * @return
	 * @throws IOException
	 */
	public static byte[] readFile(String filename) throws IOException {
		byte[] buffer = null;
		File f = new File(filename);
		synchronized(f) {
			if (!f.exists())
				return null; //f.createNewFile();
			FileInputStream fin = new FileInputStream(f);
			DataInputStream in = new DataInputStream(fin);
	        BufferedReader br = new BufferedReader(new InputStreamReader(in));
			buffer = new byte[fin.available()];
			fin.read(buffer);
		}
		return buffer;
	}

	public static String readStringFile(String filename) throws IOException {
		BufferedReader br = null;
		File f = new File(filename);
		synchronized(f) {
			if (!f.exists())
				f.createNewFile();
			FileInputStream fin = new FileInputStream(f);
			DataInputStream in = new DataInputStream(fin);
	        br = new BufferedReader(new InputStreamReader(in));
		}
		return br.readLine();
	}
	
	/**
	 * @param output
	 * @param filename
	 * @param append
	 */
	public static void saveToFile(byte[] output, String filename, boolean append) {
		try {
			File f = new File(filename);
			if (!f.exists())
				f.createNewFile();
			FileOutputStream out = new FileOutputStream(f, append);
			out.write(output);
			out.close();
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
	}

	/**
	 * @param output
	 * @param filename
	 * @return
	 */
	public static boolean saveToFile(byte[] output, String filename) {
		boolean result = true;
		try {
			File f = new File(filename);
			synchronized(f) {
				if (!f.exists())
					f.createNewFile();
				FileOutputStream out = new FileOutputStream(f, false);
				out.write(output);
				out.close();
			}
		} catch (Exception e) {
			System.out.println(e.getMessage());
			result = false;
			return result;

		}
		return result;

	}

	/**
	 * @param output
	 * @param file
	 * @return
	 */
	public static boolean saveToFile(byte[] output, File file) {
		boolean result = true;
		try {
			FileOutputStream out = new FileOutputStream(file, false);
			out.write(output);
			out.close();
		} catch (Exception e) {
			System.out.println(e.getMessage());
			result = false;
			return result;
		}
		return result;

	}

	/**
	 * @param output
	 * @param filename
	 */
	public static void updateToFile(byte[] output, String filename) {
		try {
			File f = new File(filename);
			if (!f.exists()) {
				f.createNewFile();
			} else {
//				f.delete();
//				f.createNewFile();
			}
			FileOutputStream out = new FileOutputStream(f, true);
			out.write(output);
			out.close();
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
	}
	
	public static void updateToFile2(byte[] output, String filename) {
		try {
			File f = new File(filename);
			if (!f.exists()) {
				return;
			}
			FileOutputStream out = new FileOutputStream(f, false);
			out.write(output);
			out.close();
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
	}
	
	public static void main(String[] args) {
		byte[] b = "Hello".getBytes();
		System.out.println(new String(b));
	}
}

class FileCopyException extends IOException {
	public FileCopyException(String msg) {
		super(msg);
	}
}
